<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/29/24
 * Time: 11:38 AM
 */

namespace App\Console\Commands;

use App\Models\WechatAccount;
use App\Models\WechatCorp;
use App\Services\KfAccountService;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Models\WechatCustomerData as CdModel;


/**
 * 客户数据统计
 *
 * Class Push
 * @package App\Console\Commands
 */
class WechatCustomerData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:customer_data';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '客户数据统计';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        Log::info('客户数据统计');
        $corpIds = WechatCorp::query()->pluck('corp_id')->toArray();

        try {
            $start   = strtotime(Carbon::yesterday()->startOfDay());
            $end     = strtotime(Carbon::yesterday()->endOfDay());
            $client  = new Client();
            $service = new KfAccountService();
            foreach ($corpIds as $corpId) {
                $userIds = WechatAccount::query()->where('corp_id', $corpId)->pluck('user_id')->toArray();
                if (!$userIds) {
                    continue;
                }
                $token = $service->getReplaceAccessToken($corpId);
                foreach ($userIds as $userId) {
                    $body = [
                        'headers'            => $service->headers,
                        RequestOptions::JSON => [
                            'userid'     => [$userId],
                            'start_time' => $start,
                            'end_time'   => $end,
                        ]
                    ];

                    $response = $client->request('POST', sprintf($service->api['customer_data'], $token), $body);
                    if ($response->getStatusCode() != 200) {
                        continue;
                    }
                    $contents = $response->getBody()->getContents();
                    $data     = json_decode($contents, true);
                    if ($data['errcode'] != 0) {
                        continue;
                    }
                    if (!$behaviorData = $data['behavior_data'][0] ?? []) {
                        continue;
                    }
                    $date         = Carbon::createFromTimestamp($behaviorData['stat_time'])->toDateString();
                    $customerData = CdModel::query()->firstOrNew([
                        'count_date' => $date, 'corp_id' => $corpId, 'user_id' => $userId
                    ]);

                    $customerData->message_cnt           = $behaviorData['message_cnt'] ?? 0;
                    $customerData->chat_cnt              = $behaviorData['chat_cnt'] ?? 0;
                    $customerData->reply_percentage      = $behaviorData['reply_percentage'] ?? 0.0;
                    $customerData->avg_reply_time        = $behaviorData['avg_reply_time'] ?? 0;
                    $customerData->negative_feedback_cnt = $behaviorData['negative_feedback_cnt'] ?? 0;
                    $customerData->new_apply_cnt         = $behaviorData['new_apply_cnt'] ?? 0;
                    $customerData->new_contact_cnt       = $behaviorData['new_contact_cnt'] ?? 0;
                    $customerData->save();

                }
            }
        } catch (\Exception $exception) {
            Log::error('统计客户数据失败：' . $exception->getMessage());

            return false;
        }

    }
}
